import type { InputNumberBoxEvent } from '@/components/vk-data-input-number-box/vk-data-input-number-box'
import { useGuessList } from '@/composables'
import {
  deleteMemberCartAPI,
  getMemberCartAPI,
  putMemberCartBySkuIdAPI,
  putMemberCartSelectedAPI,
} from '@/services/cart'
import { useMemberStore } from '@/stores'
import type { CartItem } from '@/types/cart'
import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'

const useCartHooks = () => {
  // 获取屏幕边界到安全区域距离
  const { safeAreaInsets } = uni.getSystemInfoSync()

  // 获取会员Store
  const memberStore = useMemberStore()

  // 获取购物车数据
  const cartList = ref<CartItem[]>([])
  // 优化购物车空列表状态，默认展示列表
  const showCartList = ref(true)
  const getMemberCartData = async () => {
    const res = await getMemberCartAPI()
    cartList.value = res.result
    showCartList.value = res.result.length > 0
  }

  // 初始化调用: 页面显示触发
  onShow(() => {
    if (memberStore.profile) {
      getMemberCartData()
    }
  })

  // 点击删除按钮
  const onDeleteCart = (skuId: string) => {
    // 弹窗二次确认
    uni.showModal({
      content: '是否删除',
      confirmColor: '#27BA9B',
      success: async (res) => {
        if (res.confirm) {
          // 后端删除单品
          await deleteMemberCartAPI({ ids: [skuId] })
          // 重新获取列表
          getMemberCartData()
        }
      },
    })
  }

  // 修改商品数量
  const onChangeCount = (ev: InputNumberBoxEvent) => {
    putMemberCartBySkuIdAPI(ev.index, { count: ev.value })
  }

  // 修改选中状态-单品修改
  const onChangeSelected = (item: CartItem) => {
    // 前端数据更新-是否选中取反
    item.selected = !item.selected
    // 后端数据更新
    putMemberCartBySkuIdAPI(item.skuId, { selected: item.selected })
  }

  // 计算全选状态
  const isSelectedAll = computed(() => {
    return cartList.value.length && cartList.value.every((v) => v.selected)
  })

  // 修改选中状态-全选修改
  const onChangeSelectedAll = () => {
    // 全选状态取反
    const _isSelectedAll = !isSelectedAll.value
    // 前端数据更新
    cartList.value.forEach((item) => {
      item.selected = _isSelectedAll
    })
    // 后端数据更新
    putMemberCartSelectedAPI({ selected: _isSelectedAll })
  }

  // 计算选中单品列表
  const selectedCartList = computed(() => {
    return cartList.value.filter((v) => v.selected)
  })

  // 计算选中总件数
  const selectedCartListCount = computed(() => {
    return selectedCartList.value.reduce((sum, item) => sum + item.count, 0)
  })

  // 计算选中总金额
  const selectedCartListMoney = computed(() => {
    return selectedCartList.value
      .reduce((sum, item) => sum + item.count * item.nowPrice, 0)
      .toFixed(2)
  })

  // 结算按钮
  const gotoPayment = () => {
    if (selectedCartListCount.value === 0) {
      return uni.showToast({
        icon: 'none',
        title: '请选择商品',
      })
    }
    // 跳转到结算页
    uni.navigateTo({ url: '/pagesOrder/create/create' })
  }

  // 猜你喜欢
  const { guessRef, onScrolltolower } = useGuessList()
  return {
    onScrolltolower,
    memberStore,
    showCartList,
    cartList,
    onChangeSelected,
    onChangeCount,
    onDeleteCart,
    safeAreaInsets,
    onChangeSelectedAll,
    isSelectedAll,
    selectedCartListMoney,
    gotoPayment,
    selectedCartListCount,
    guessRef,
  }
}

export default useCartHooks
